package com.beiing.tianshuai.tianshuai.activity;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.MyApplication;
import com.beiing.tianshuai.tianshuai.entity.SplashBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.freshnews.DiscoveryDetailActivity;
import com.beiing.tianshuai.tianshuai.huodong.ActivitiesDetailActivity;
import com.beiing.tianshuai.tianshuai.interest.InterestVideoDetailActivity;
import com.beiing.tianshuai.tianshuai.presenter.SplashPresenter;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.view.SplashViewImpl;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;
import cn.magicwindow.MLinkAPIFactory;
import cn.magicwindow.MWConfiguration;
import cn.magicwindow.MagicWindowSDK;
import cn.magicwindow.Session;
import cn.magicwindow.mlink.MLinkCallback;
import cn.magicwindow.mlink.MLinkIntentBuilder;
import cn.magicwindow.mlink.annotation.MLinkDefaultRouter;

/**
 * Created by Jinda Yang on 2017/8/9
 */
@MLinkDefaultRouter
public class SplashActivity extends Activity implements SplashViewImpl {

    @BindView(R.id.tv_break)
    TextView mTvPass;
    @BindView(R.id.iv_add_container)
    ImageView mIvAdd;

    private AnimatorSet mSet = new AnimatorSet();
    private static final String TAG = "SplashActivity";
    private static final int ANIM_TIME = 3000;
    private static final float SCALE_END = 1F;
    private Unbinder mUnbinder;
    private Context mContext;
    private TimeCount mCountDown;
    private String url = null;

    /**
     * 声明一个数组，用来存储所有需要动态申请的权限
     */
    @SuppressLint("InlinedApi")
    private String[] permissions = new String[]{
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE};
    /**
     * 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
     */
    private List<String> mPermissionList = new ArrayList<>();
    private String mTypeName = "4";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MLinkAPIFactory.createAPI(this).registerWithAnnotation(this);
        initStatusBar();
        setContentView(R.layout.activity_splash);
        mUnbinder = ButterKnife.bind(this);
        mContext = this;
        initMagicWindow();
        //跳转router调用
        if (getIntent().getData() != null) {
            MLinkAPIFactory.createAPI(this).router(getIntent().getData());
            finish();
        } else {
            //如果需要应用宝跳转，则调用。否则不需要
            MLinkAPIFactory.createAPI(this).checkYYB();
            SharedPreferences sp = this.getSharedPreferences("isFirstLaunch", MODE_PRIVATE);
            initListener();
            if (!sp.getBoolean("isFirstEnter", false)) {
                startActivity(new Intent(mContext, GuideActivity.class));
                finish();
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    LogUtils.i("checkVersion", "SplashActivity");
                    checkPermission();
                } else {
                    initPresenter();
                }
            }
        }
    }

    /**
     * 初始化魔创相关功能
     */
    private void initMagicWindow() {
        MWConfiguration config = new MWConfiguration(this);
        config.setLogEnable(true)
                .setSharePlatform(MWConfiguration.ORIGINAL);
        ;
        MagicWindowSDK.initSDK(config);
        MLinkAPIFactory.createAPI(this).registerWithAnnotation(this);
        mLinkAPIRegister(this);
    }

    private void mLinkAPIRegister(Context context) {
        MLinkAPIFactory.createAPI(context).registerDefault(new MLinkCallback() {
            @Override
            public void execute(Map<String, String> map, Uri uri, Context context) {
                MLinkIntentBuilder.buildIntent(context, MainActivity.class);
            }
        });
        // tinsine_video:  mLink 的 key, mLink的唯一标识
        MLinkAPIFactory.createAPI(context).register("tinsine_video", new MLinkCallback() {
            @Override
            public void execute(Map<String, String> map, Uri uri, Context context) {
                Intent intent = new Intent(context, InterestVideoDetailActivity.class);
                intent.putExtra("vid", map.get("id"));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                context.startActivity(intent);
            }
        });
        // tinsine_video:  mLink 的 key, mLink的唯一标识
        MLinkAPIFactory.createAPI(context).register("tinsine_active", new MLinkCallback() {
            @Override
            public void execute(Map<String, String> map, Uri uri, Context context) {
                Intent intent = new Intent(context, ActivitiesDetailActivity.class);
                intent.putExtra("active_id", map.get("id"));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                context.startActivity(intent);
            }
        });
        // tinsine_video:  mLink 的 key, mLink的唯一标识
        MLinkAPIFactory.createAPI(context).register("tinsine_news", new MLinkCallback() {
            @Override
            public void execute(Map<String, String> map, Uri uri, Context context) {
                Intent intent = new Intent(context, DiscoveryDetailActivity.class);
                intent.putExtra("fresh_id", map.get("id"));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                context.startActivity(intent);
            }
        });
    }

    private void initStatusBar() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 键type_name = 0 活动  1  视频  2  新鲜事   3  第三方 4 不跳转
     */
    private void initListener() {
        mTvPass.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                startActivity(new Intent(mContext, MainActivity.class));
                finish();
            }
        });

        mIvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String uid = UserInfoBean.getUid(mContext);
                if (TextUtils.isEmpty(uid)) {
                    return;
                }
                Intent intent = new Intent(mContext, MainActivity.class);
                switch (mTypeName) {
                    case "0":
                        intent.putExtra("url", url);
                        intent.putExtra("intentType", 0);
                        startActivity(intent);
                        mSet.removeAllListeners();
                        finish();
                        break;
                    case "1":
                        intent.putExtra("url", url);
                        intent.putExtra("intentType", 1);
                        startActivity(intent);
                        mSet.removeAllListeners();
                        finish();
                        break;
                    case "2":
                        intent.putExtra("url", url);
                        intent.putExtra("intentType", 2);
                        startActivity(intent);
                        mSet.removeAllListeners();
                        finish();
                        break;
                    case "3":
                        intent.putExtra("url", url);
                        intent.putExtra("intentType", 3);
                        startActivity(intent);
                        mSet.removeAllListeners();
                        finish();
                        break;
                    case "4":
                        break;
                    default:
                }
            }
        });
    }

    private void initPresenter() {
        SplashPresenter presenter = new SplashPresenter(this);
        presenter.getSplashInfo();
    }

    private void startMainActivity(String picName) {
        RequestOptions avatarOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop();
        Glide.with(mContext.getApplicationContext())
                .load(picName)
                .apply(avatarOptions)
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, Transition<? super Drawable> transition) {
                        if (mIvAdd != null) {
                            mIvAdd.setImageDrawable(resource);
                        }
                        startAnim();
                    }
                });
//        Glide.with(mContext.getApplicationContext())
//                .load(picName)
//                .apply(avatarOptions)
//                .into(mIvAdd);
    }

    private void startAnim() {

        ObjectAnimator animatorX = ObjectAnimator.ofFloat(mIvAdd, "scaleX", 1f, SCALE_END);
        ObjectAnimator animatorY = ObjectAnimator.ofFloat(mIvAdd, "scaleY", 1f, SCALE_END);
        mTvPass.setVisibility(View.VISIBLE);
        mCountDown = new TimeCount(4000, 1000);
        mCountDown.start();
        mSet.setDuration(ANIM_TIME).play(animatorX).with(animatorY);
        mSet.start();
        mSet.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                startActivity(new Intent(mContext, MainActivity.class));
                finish();
            }
        });
    }

    /**
     * 拦截用户返回操作
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return keyCode == KeyEvent.KEYCODE_BACK || super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
        if (mCountDown != null) {
            mCountDown.cancel();
        }
        super.onDestroy();
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void onRequestSuccess(SplashBean bean) {
        SplashBean.DataBean data = bean.getData();
        String picName = data.getPicname();
        url = data.getLink();
        mTypeName = data.getTypeName();
        startMainActivity(picName);
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        LogUtils.e(throwable.toString(), TAG);
        startActivity(new Intent(mContext, MainActivity.class));
        finish();
    }

    private void checkPermission() {
        mPermissionList.clear();
        /*
         * 判断哪些权限未授予
         * 以便必要的时候重新申请
         */
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(mContext, permission) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permission);
            }
        }
        /*
         * 判断存储委授予权限的集合是否为空
         */
        if (!mPermissionList.isEmpty()) {
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(SplashActivity.this, permissions, 1);
        } else {//未授予的权限为空，表示都授予了
            initPresenter();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                initPresenter();
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }

    /**
     * 获取验证码计时器
     */
    private class TimeCount extends CountDownTimer {

        TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onFinish() {
            if (mTvPass != null) {
                mTvPass.setText("跳过 0S");
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {
            long l = millisUntilFinished / 1000;
            if (mTvPass != null) {
                mTvPass.setText(MessageFormat.format("跳过 {0}S", String.valueOf(l)));
            }
        }
    }

    @Override
    protected void onPause() {
        Session.onPause(this);
        super.onPause();
    }

    @Override
    protected void onResume() {
        Session.onResume(this);
        super.onResume();
    }
}